<template>
    <div class="page-wrap">
        <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
            <div class="addressIcon"></div>
            <span>当前位置：</span>
            <span style="cursor: pointer" @click="returnImage($route.query.page)">{{pageTitle}}</span>
            <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
            <span style="color: #333">{{caseDetail.name}}</span>
        </div> -->
        <div class="page-content">
            <div class="img-header">
                <div style="font-weight: 700;font-size: 18px">编辑{{ pageTitle }}</div>
            </div>
            <Divider />
            <div class="content-wrap">
                <StepList
                    :data="stepList"
                    :current="currentStep"
                    @change-step="gotoStep"
                    style="margin-bottom:20px"
                ></StepList>
                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120" style="width: 500px" v-show="currentStep === 1">
                    <FormItem label="案例名称" prop="name">
                        <Input v-model.trim="formValidate.name" placeholder='名称不能包含下列任意英文字符 \ / : * ? " < > |,长度为1-40个字符'></Input>
                    </FormItem>
                    <FormItem label="描述" prop="desc">
                        <Input v-model.trim="formValidate.description" type="textarea" :maxlength="200" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></Input>
                    </FormItem>
                    <FormItem label="封面图片" prop="logo">
                        <item-upload
                            :showChooseBtn="true"
                            @upload-success="changeImage" 
                            @del-image="changeImage()"
                            fileType="images"
                            :isSingle="true"
                            :fileList="imageList"
                            :formatArr="['jpg','jpeg','png']"></item-upload>
                    </FormItem>
                    <FormItem label="绑定文档" prop="fileListIDs">
                        <item-upload
                            :showChooseBtn="true"
                            @upload-success="bindDocument" 
                            @del-item="delDocument"
                            @del-item-fildId="delDocumentFildId"
                            fileType="docs"
                            :download="true"
                            :fileList="documentList"
                            :formatArr="['pdf','doc','docx','xls','xlsx','xla','pptx','pps','ppt','rtf','txt','md']"></item-upload>
                    </FormItem>
                    <FormItem label="绑定视频" prop="video">
                        <item-upload
                            :showChooseBtn="true"
                            @upload-success="bindVideo" 
                            @del-item="delVideo"
                            @del-item-fildId="delVideoFildId"
                            fileType="videos"
                            :download="true"
                            :fileList="videoList"
                            :formatArr="['mp4','webm','ogv','ogg','3gp','3g2','m4v','mpg','vob','fli','mkv','asf','asx','wmv','flv','avi']"></item-upload>
                    </FormItem>
                    <FormItem label="绑定工具" prop="tool">
                        <item-upload
                            :showChooseBtn="true"
                            @upload-success="bindTool" 
                            @del-item="delTool"
                            @del-item-fildId="delToolFildId"
                            :download="true"
                            :allFileType="true"
                            :fileList="toolList"></item-upload>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="uploadCase" class="mr6">下一步</Button>
                        <Button @click="returnImage($route.query.page)">返回列表页</Button>
                    </FormItem>
                </Form>
                <div v-show="currentStep === 2">
                    <Alert v-if="caseDetail.tmplName">已绑定模板：{{caseDetail.tmplName}}</Alert>
                    <Tabs v-model="tabName" type="card">
                        <TabPane label="编辑拓扑" name="topo">
                            <div v-show="tabName === 'topo'">
                                <Alert type="warning" show-icon>
                                    <p>提示：</p>
                                    <p>1. 本步骤提供模板生成功能，操作步骤：进入拓扑编辑页面（绘制拓扑）> 生成工程模板</p>
                                    <p>2. 若拓扑结构有修改，请在编辑后重新生成模板</p>
                                    <p>3. 重新生成的模板将会替换原有模板</p>
                                </Alert>
                                <Button type="primary" @click="createTop" style="margin-right: 6px;">编辑拓扑</Button>
                                <Button type="primary" @click="createProjectTemplate" :disabled="!proId">生成工程模板</Button>
                            </div>
                        </TabPane>
                        <TabPane label="镜像选择" name="vm" v-if="!templateId||[22].includes(deployStatus)">
                            <div v-show="tabName === 'vm'">
                                <Alert type="warning" show-icon>
                                    <p>提示：</p>
                                    <p>1. 本步骤提供模板生成功能，操作步骤：创建机器（选择镜像、配额、机器数量）> 生成工程模板</p>
                                    <p>2. 若机器数据有修改，请在改动后重新生成模板</p>
                                    <p>3. 重新生成的模板将会替换原有模板</p>
                                </Alert>
                                <GenerateTemplate
                                    :clearBash="true"
                                    ref="generateTemplate"
                                    @on-success="changeProjectAndTemplate"
                                ></GenerateTemplate>
                            </div>
                        </TabPane>
                    </Tabs>
                    <div class="mt20">
                        <Button type="primary" @click="currentStep -= 1" class="mr6">上一步</Button>
                        <Button type="primary" @click="currentStep += 1" class="mr6" :disabled="!this.caseDetail.tmplId">下一步</Button>
                        <Button @click="returnImage($route.query.page)">返回列表页</Button>
                    </div>
                </div>
                <div v-show="currentStep === 3">
                    <Alert type="warning" show-icon style="margin-top: 20px;">
                        <p>提示：本步骤是对模板中的设备进行编辑，操作步骤：部署工程 > 接入虚拟机(操作) > 关机 > 生成镜像 > 设置接入机器 > 保存</p>
                    </Alert>
                    <Progress :percent="deployProcess" :stroke-width="20" :status="progresStatus" text-inside v-show="[9, 13, 15].includes(deployStatus)" style="margin-bottom: 10px;"/>
                    <div class="btn-group">
                        <div>
                            <Button type="primary" @click="deploy" :loading="deployLoading && [9, 13, 15,22].includes(deployStatus)" 
                                :disabled="deployLoading || [3, 9, 13, 15].includes(deployStatus)"
                                style="margin-right: 6px;">部署</Button>
                            <Poptip
                                confirm
                                title="确定要销毁吗?"
                                :disabled="destroyLoading || [9, 13, 15].includes(deployStatus)"
                                v-show="[3, 13].includes(deployStatus)"
                                @on-ok="destroy">
                                <Button type="error" :loading="destroyLoading || deployStatus === 9">销毁</Button>
                            </Poptip>
                        </div>
                        <!-- 暂不提供销毁倒计时与延迟销毁功能 -->
                        <!-- <div v-show="[3].includes(deployStatus)">
                            <div class="count-down">
                                环境销毁倒计时：
                                <span>{{time.h}}</span>:<span>{{time.m}}</span>:<span>{{time.s}}</span>
                            </div>
                            <Poptip
                                confirm
                                title="每次延长时间为24个小时，确认延长销毁时间?"
                                @on-ok="extendDestroyTime"
                                v-if="destroyStatus && proId && leftTime > 0"
                                transfer
                                word-wrap
                                width="200"
                            >
                                <Button type="primary">延长销毁时间</Button>
                            </Poptip>
                        </div> -->
                    </div>
                    <EnvironManage
                        :prjId="proId"
                        :caseId="caseDetail.id"
                        :caseName="caseDetail.name"
                        :accessName="caseDetail.accessName"
                        :templateId="templateId"
                        v-if="proId && deployStatus == 3"
                        @setImageList="getImageList"
                        @setAccess="setAccess"
                        style="margin-top: 20px;"
                    ></EnvironManage>
                    <ImageList
                        ref="imageList"
                        :prjId="proId"
                        v-if="proId"
                        style="margin-top:30px;"
                        @on-generate-finish="getGenerateImageList"
                    ></ImageList>
                    <SaveExper
                        :prjId="proId"
                        :caseId="caseDetail.id"
                        :caseName="caseDetail.name"
                        :envTemplateId="templateId"
                        :deployStatus="deployStatus"
                        :disabled="generateImageList.length === 0"
                        :accessName="caseDetail.accessName"
                        @setReplaceTotal="getReplaceTotal"
                        @getExperStatus="getDetail"
                    >
                    </SaveExper>
                    <div class="mt20">
                        <Button type="primary" @click="currentStep -= 1" class="mr6">上一步</Button>
                        <Button @click="returnImage($route.query.page)">返回列表页</Button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import { validateName,validateName128 } from '@/libs/reg'
    import { getCaseAnalyseDetail, updateCaseAnalyse, bindFile, unbindFile } from '@/api/event'
    import { getProjects, queryNetworkList } from '@/api/drill_compete'
    import { createTemplate } from '@/api/proTemplate'
    import { getstatusbyprjid } from '@/api/drill'
    import { clearProject } from '@/api/competition'
    import { creatBlankPro, deployProject, getDeployProgress } from '@/api/homer'
    import { getTime } from '@/api/selfStudy/courseExp'
    import ItemUpload from '@/components/item-upload'
    import StepList from '@/components/step-list';
    import EnvironManage from './environManage';
    import ImageList from './createImageList';
    import SaveExper from './saveExper';
    import GenerateTemplate from '@/components/generate-template';
    import pageTitle from '@/mixin/pageTitle';
    export default {
        mixins: [pageTitle],
        components: {
            StepList,
            ItemUpload,
            EnvironManage,
            ImageList,
            SaveExper,
            GenerateTemplate
        },
        data() {
            return {
                deploySucceed: false,
                destroySucceed: false,
                tabName: 'topo',
                replaceTotal: 0,
                generateImageList: [], //生成的镜像列表
                progresStatus: 'active',
                errorMessage: '',
                time: {},
                deployProcess: 0, //部署进度
                deployStatus: 0, //部署状态
                deployLoading: false,
                destroyLoading: false,
                currentStep: 1,
                uploadAction: "/api/minio/upload/permanent",
                uploadHeader: {
                    Authorization: localStorage.token,
                    Accept: '*/*'
                },
                formValidate: {
                    name: '',
                    description: '',
                    fileListIDs: '',
                    tmplId: ''
                },
                ruleValidate: {
                    name: [
                        {
                            required: true,
                            max: 40,
                            message: '案例名称长度为1—40个字符',
                            trigger: 'change'
                        },
                        {
                            validator: validateName,
                            trigger: 'change'
                        }
                    ]
                },
                imageList: [],
                documentList: [],
                videoList: [],
                toolList: [],
                caseDetail: {},
                relevanceStepFinishStatus: false,
                hasNode: false
            }
        },
        created() {
        },
        computed: {
            templateId() {
                return this.caseDetail.tmplId
            },
            proId() {
                return this.caseDetail.projectId
            },
            stepList() {
                return [
                    {
                        title: '基础信息',
                        show: true,
                        name: 'baseInfo',
                        finish: this.caseDetail.id ? true : false
                    },
                    {
                        title: '案例环境',
                        name: 'relevance',
                        show: true,
                        finish: this.caseDetail.tmplId ? true : false
                    },
                    {
                        title: '部署环境',
                        name: 'deploy',
                        show: true,
                        finish: this.replaceTotal > 0 ? true : false
                    }
                ];
            },
        },
        mounted() {
            this.getDetail()
        },
        beforeRouteLeave(to, from, next) {
            if(to.path === '/caseAnalyse') {
                next()
            } else {
                sessionStorage.removeItem('queryObj');
                next()
            }
        },
        watch: {
            documentList(list) {
                this.$set(this.formValidate, 'fileListIDs', list.map(item => item.id).join())
                this.$refs.formValidate.validateField('fileListIDs')
            },
            tabName() {
                this.$refs.generateTemplate.resetFields()
            },
            deploySucceed(newValue) { // 部署成功，查询工程状态，视情况查询部署进度
                if (newValue) {
                    this.getProjectDetail()
                }
            },
            destroySucceed(newValue) { // 清空工程成功，查询工程状态
                if (newValue) {
                    this.getProjectDetail()
                }
            },
            // 保存了工程模板后，需要重置案例环境步骤为编辑拓扑
            templateId() {
                this.tabName = 'topo'
            }
        },
        methods: {
            changeProjectAndTemplate(obj) {
                this.createProject(obj.id, true, obj.name)
            },
            getReplaceTotal(total) {
                this.replaceTotal = total;
                if (total > 0) {
                    this.$emit('on-finish', true);
                }
            },
            getGenerateImageList(list) {
                this.generateImageList = list;
            },
            // 设置名称
            setAccess(name) {
                this.$set(this.caseDetail, 'accessName', name)
            },
            // 获取镜像列表
            getImageList() {
                if (this.proId) {
                    this.$refs.imageList.getCreateImageList();
                }
            },
            // 获取工程销毁时间
            getTime() {
                getTime(this.proId).then(({ code, message, attribute = {} }) => {
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    this.countdown(attribute.destroyTime || 0)
                }).catch(() => {
                    this.$Message.error('获取销毁倒计时异常')
                })
            },
            countdown(intervalTime) {
                let h = '00', m = '00', s = '00';
                if (intervalTime && intervalTime > 0) {
                    h = Math.floor(intervalTime / 1000 / 60 / 60).toString().padStart(2, '0');
                    m = Math.floor(intervalTime / 1000 / 60 % 60).toString().padStart(2, '0');
                    s = Math.floor(intervalTime / 1000 % 60).toString().padStart(2, '0');
                    this.countdownTimer = setTimeout(() => {
                        this.countdown(intervalTime - 1000)
                    })
                } else {
                    clearTimeout(this.countdownTimer)
                }
                this.time = {h, m, s};
            },
            // 获取工程详情
            getProjectDetail() {
                let projectId = this.proId
                if (!projectId) {
                    this.deployLoading = false
                    this.destroyLoading = false
                    // 清空数据，控制页面内容的隐藏
                    this.deployStatus = 0
                    this.generateImageList = []
                    return
                }
                getstatusbyprjid(projectId).then(data => {
                    let { code, attribute, message } = data
                    if (code !== 1) {
                        this.$Message.warning(message)
                        this.deployLoading = false
                        this.destroyLoading = false
                        return
                    }
                    let project = attribute.project
                    if (project.errorMessage) {
                        this.$Message.warning(project.errorMessage)
                        clearTimeout(this.timeOut)
                        return
                    }
                    this.deployStatus = project.status
                    this.deployId = project.deployId
                    if (![0, 3, 6, 10].includes(project.status)) { // 非‘未部署’、‘部署成功’、‘部署失败’、‘未绑定工程’状态，需要查询部署进度
                        this.getDeployProgress()
                    } else {
                        clearTimeout(this.timeOut)
                    }
                    // 暂不提供销毁倒计时功能
                    // if (project.status === 3) { // 部署成功，获取工程销毁时间
                    //     this.getTime()
                    // }
                }).catch(() => {
                    this.$Message.error('获取工程详情异常')
                })
            },
            getProjectDeployDetail(id, isdeploy) {
                getstatusbyprjid(id).then(data => {
                    let { code, attribute, message } = data
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    let project = attribute.project
                    if (project.errorMessage) {
                        this.$Message.warning(project.errorMessage)
                        this.deployLoading = false
                        this.deployStatus = 22
                        return
                    }
                    if (project.checkOuts && project.checkOuts.length) {
                        project.checkOuts.forEach(item => {
                            let name = []
                            if (item.data) {
                                item.data.forEach(subItem => {
                                    name.push(subItem.name)
                                })
                            }
                            if (name.length) {
                                this.$Message.warning(`${name.join(', ')}${item.message}`)
                            }
                        })
                        return
                    }
                    this.deployStatus = project.status
                    if (project.status === 15) {
                        setTimeout(() => {
                            this.getProjectDeployDetail(id, isdeploy)
                        }, 3000)
                    } else {
                        isdeploy ? this.deploySucceed = true : this.destroySucceed = true
                    }
                })
            },
            // 获取部署进度
            getDeployProgress() {
                if (!this.deployId) {
                    return
                }
                getDeployProgress(this.deployId).then(res => {
                    let { data } = res
                    let { code, message } = data
                    data = data.data
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    this.deployProcess = data.process
                    if (data.deployStatus === 1) { // 还在部署中，持续获取部署进度
                        this.progresStatus = 'active'
                        this.timeOut = setTimeout(() => {
                            this.getDeployProgress()
                        }, 5000)
                    } else if (data.deployStatus === -1) { // 部署失败
                        this.progresStatus = 'active'
                        this.getProjectDetail()
                    } else if (data.deployStatus === 0) { // 部署成功
                        this.progresStatus = ''
                        this.getProjectDetail()
                        this.deployLoading = false
                        this.$Message.success('部署成功')
                    }
                }).catch(() => {
                    this.$Message.error('获取部署进度异常')
                })
            },
            // 部署环境
            async deploy() {
                if (!this.proId) { // 已经没有工程ID，使用工程模板新建一个工程
                    await this.createProject(this.templateId, true)
                }
                this.$nextTick(() => {
                    let params = {
                        pageIndex: 1,
                        pageSize: 10,
                        id: this.proId
                    }
                    this.deploySucceed = false
                    this.destroyLoading = false // 每次部署环境，都将销毁按钮的状态重置
                    this.deployLoading = true
                    getProjects(params).then(({ code, message, data = {} }) => {
                        if (code !== 1) {
                            this.$Message.warning(message)
                            return
                        }
                        let items = data.items || []
                        if (items[0].status === 17) {
                            this.$Message.warning(`工程导入失败：${items[0].errorMessage}`)
                            this.deployLoading = false
                            this.deployStatus = 22
                            return
                        }
                        if (items[0].status === 4) {
                            this.$Message.warning(`工程正在删除中，禁止重新部署`)
                            return
                        }
                        // 部署前清空部署进度
                        this.progresStatus = 'active'
                        this.deployProcess = 0
                        deployProject(this.proId).then(({ data = {} }) => {
                            let { code, message } = data
                            if (code === 1) { // 部署成功，获取部署状态
                                this.getProjectDetail(this.proId)
                            } else if (code === 3) { // 校验中，持续获取部署状态
                                this.getProjectDeployDetail(this.proId, true)
                            } else {
                                this.$Message.warning(message)
                                this.deployLoading = false
                            }
                        }).catch(() => {
                            this.$Message.error('部署异常')
                        })
                    }).catch(() => {
                        this.$Message.error('查询工程状态异常，无法部署')
                    })
                })
            },
            // 销毁环境
            destroy() {
                // 销毁前同样需要清空部署进度
                this.progresStatus = 'active'
                this.deployProcess = 0
                this.destroyLoading = true
                clearProject(this.proId).then(({ code, message }) => {
                    if ([1].includes(code)) { // 销毁成功，校验中，均获取部署状态
                        this.getProjectDetail(this.proId)
                    } else if ([3].includes(code)) {
                        this.getProjectDeployDetail(this.proId, false)
                    } else {
                        this.$Message.warning(message)
                        this.destroyLoading = false
                    }
                }).catch(() => {
                    this.$Message.error('销毁异常')
                })
            },
            // 判断工程中是否存在节点
            getHasNode() {
                return new Promise(resolve => {
                    getstatusbyprjid(this.proId).then(({ code, attribute = {} }) => {
                        if (code === 1) {
                            let network = attribute.network || {}
                            if (network.id) {
                                queryNetworkList(this.proId, network.id).then(({ code, attribute = {} }) => {
                                    if (code === 1 && attribute.editorStage && attribute.editorStage.deviceNum) {
                                        this.hasNode = true
                                        resolve()
                                    } else {
                                        resolve()
                                    }
                                }).catch(() => {
                                    resolve()
                                })
                            } else {
                                resolve()
                            }
                        } else {
                            resolve()
                        }
                    }).catch(() => {
                        resolve()
                    })
                })
            },
            // 创建工程模板
            async createProjectTemplate() {
                // 判断工程中是否存在虚拟机节点，没有节点不允许创建工程模板
                await this.getHasNode()
                if (this.hasNode) {
                    createTemplate({
                        description: '',
                        markType: '',
                        name: this.caseDetail.name,
                        picUrl: '',
                        projectId: this.proId,
                        visibility: 'share'
                    }).then(({ data = {} }) => {
                        let { code, message } = data
                        if (code !== 1) {
                            this.$Message.warning(message)
                            return
                        }
                        // 模板创建完毕，绑定工程与模板关联关系
                        let obj = {
                            id: this.caseDetail.id,
                            tmplId: data.data,
                            tmplName: this.caseDetail.name // 这种方式创建的工程模板名称，会与案例复盘名称保持一致
                        }
                        updateCaseAnalyse(obj).then(({ code, message }) => {
                            if(code !== 1){
                                this.$Message.warning(message)
                                return
                            }
                            this.$set(this.formValidate, 'tmplId', data.data)
                            this.$set(this.caseDetail, 'tmplId', data.data)
                            this.$set(this.caseDetail, 'tmplName', this.caseDetail.name)
                            this.$Message.success('生成工程模板成功')
                            this.currentStep += 1
                        }).catch(() => {
                            this.$Message.error('修改案例工程异常')
                        })
                    }).catch(() => {
                        this.$Message.error('生成模板异常')
                    })
                } else {
                    this.$Message.warning('还没有进行拓扑编辑，请先进行拓扑编辑')
                }
            },
            // 创建拓扑
            async createTop() {
                if (!this.proId) { // 没有工程
                    this.createProject(this.caseDetail.tmplId) // 创建工程并跳转
                } else { // 存在工程
                    let status =  await this.getProjectDetails(this.proId)
                    if (status !== 1) { // 查看工程ID是否还存在，不存在重新创建并绑定，存在直接跳转
                        this.createProject(this.caseDetail.tmplId)
                    } else {
                        window.openTrain(`/jjzzTopo/index.html#/ProjectViews?projectId=${this.proId}`);
                    }
                }
            },
            // 查询工程是否存在
            getProjectDetails(id) {
                return new Promise((resolve, reject) => {
                    let params = {
                        pageIndex: 1,
                        pageSize: 10,
                        id
                    }
                    getProjects(params).then(data => {
                        // 存在工程，允许跳转
                        if (data.code == 1 && data.data.items.length > 0 && ![4, 17].includes(data.data.items[0].status)) {
                            resolve(1);
                        } else {
                            resolve(0);
                        }
                        resolve(1);
                    }).catch(error => {
                        resolve(0);
                    })
                })
            },
            // 创建工程，并绑定工程与案例关联关系，关系绑定完成后，跳转至拓扑图页面
            createProject(tmplId, notNeedJump, tmplName) {
                return new Promise((resolve) => {
                    creatBlankPro(tmplId ? tmplId : '', {
                        mode: "complete",
                        name: this.formValidate.name,
                        quotaTypeId: "2",
                        trainId: 0,
                        type: "normal",
                    }, 'complete').then(({ data = {} }) => {
                        let { code, message, attribute } = data
                        if(![1, 2].includes(code)){ // 成功或导入中均不需要报错
                            this.$Message.warning(message)
                            return
                        }
                        let result = attribute.result
                        // 工程创建完毕，绑定工程与案例关联关系
                        data = {
                            id: this.caseDetail.id,
                            projectId: result.id,
                            tmplId,
                            tmplName: tmplName ? tmplName : undefined // 有值的情况下修改，没值做不修改，传undefined
                        }
                        updateCaseAnalyse(data).then(({ code, message }) => {
                            if(code !== 1){
                                this.$Message.warning(message)
                                return
                            }
                            this.$set(this.caseDetail, 'projectId', result.id)
                            this.$set(this.caseDetail, 'tmplId', tmplId)
                            if (tmplName) { // 没值不修改这个值
                                this.$set(this.caseDetail, 'tmplName', tmplName)
                            }
                            if (notNeedJump) { // 不需要跳转页面，不需要跳转并提示信息
                                if (this.currentStep !== 3) {
                                    this.currentStep += 1
                                }
                                return
                            }
                            this.$Message.success('正在跳转至拓扑编辑页面，请确保窗口未被拦截')
                            window.openTrain(`/jjzzTopo/index.html#/ProjectViews?projectId=${result.id}`);
                        }).catch(() => {
                            this.$Message.error('修改案例工程异常')
                        }).finally(() => {
                            resolve()
                        })
                    }).catch(() => {
                        this.$Message.error('创建拓扑图异常')
                        resolve()
                    })
                })
            },
            // 修改案例基础信息
            uploadCase(event) {
                this.$refs.formValidate.validate(valid => {
                    if (valid) {
                        let data = {
                            id: this.formValidate.id,
                            name: this.formValidate.name,
                            description: this.formValidate.description
                        }
                        updateCaseAnalyse(data).then(({ code, message }) => {
                            if(code !== 1){
                                this.$Message.warning(message)
                                return
                            }
                            this.caseDetail.name = this.formValidate.name
                            this.caseDetail.description = this.formValidate.description
                            this.$Message.success('编辑基础信息成功')
                            if (event) { // 点击下一步的操作，需要递增
                                this.currentStep += 1
                            }
                        }).catch(() => {
                            this.$Message.error('编辑基础信息异常')
                        })
                    } else {
                        this.$Message.warning('请完善信息')
                    }
                })
            },
            // 将上传文件与案例绑定关系
            bindTool(tool) {
                this.bindFile(tool, 1)
            },
            bindDocument(document) {
                this.bindFile(document, 2)
            },
            bindVideo(video) {
                this.bindFile(video, 3)
            },
            delDocumentFildId(fildId) {
                let template = this.documentList.find(item => item.fileId === fildId) || {}
                this.delDocument(template.id)
            },
            delVideoFildId(fildId) {
                let template = this.videoList.find(item => item.fileId === fildId) || {}
                this.delVideo(template.id)
            },
            delToolFildId(fildId) {
                let template = this.toolList.find(item => item.fileId === fildId) || {}
                this.delTool(template.id)
            },
            // 解绑关系
            delTool(id) {
                this.unbindFile(id, 1)
            },
            delDocument(id) {
                this.unbindFile(id, 2)
            },
            delVideo(id) {
                this.unbindFile(id, 3)
            },
            // 删除文件列表中对应数据
            removeItem4List(list, id) {
                let index = list.findIndex(item => item.id === id)
                if (index !== -1) {
                    list.splice(index, 1)
                }
            },
            // 统一的解绑操作
            unbindFile(id, type) {
                unbindFile(id).then(({ code, message }) => {
                    if(code !== 1){
                        this.$Message.warning(message)
                        return
                    }
                    let list = type === 1 ? this.toolList : type === 2 ? this.documentList : this.videoList
                    this.removeItem4List(list, id)
                    this.$Message.success('解绑成功')
                }).catch(() => {
                    this.$Message.error('解绑异常')
                })
            },
            // 统一的绑定文件操作
            bindFile(file, type) {
                let obj = {
                    caseId: this.caseDetail.id,
                    fileId: file.fileId,
                    fileName: file.fileName,
                    path: file.filePath,
                    type
                }
                bindFile(obj).then(({ code, message, data }) => {
                    if(code !== 1){
                        this.$Message.warning(message)
                        return
                    }
                    obj.id = data
                    type === 1 ? this.toolList.push(obj) : type === 2 ? this.documentList.push(obj) : this.videoList.push(obj)
                    this.$Message.success('绑定成功')
                }).catch(() => {
                    this.$Message.error('绑定异常')
                })
            },
            // 步骤跳转
            gotoStep(step) {
                if (step === 3 && !this.templateId) {
                    this.$Message.warning('请先设置好案例环境再进行部署操作')
                    return
                }
                if (this.currentStep === 1) { // 当前是第一步，需要先保存数据
                    this.uploadCase()
                }
                this.currentStep = step;
            },
            changeImage(file) {
                let data = {
                    id: this.caseDetail.id,
                    iconPath: file ? file.filePath : ''
                }
                updateCaseAnalyse(data).then(({ code, message }) => {
                    if(code !== 1){
                        this.$Message.warning(message)
                        return
                    }
                    if (file) {
                        this.$Message.success('替换封面图片成功')
                        this.imageList = [{
                            path: file.filePath
                        }]
                    } else {
                        this.$Message.success('删除封面图片成功')
                        this.imageList = []
                    }
                }).catch(() => {
                    this.$Message.error(`${file ? '替换' : '删除'}封面图片异常`)
                })
            },
            // 返回课件列表
            returnImage(page){
                this.$router.push({
                    name: 'caseAnalyse',
                    params:{
                    	page:page
                    }
                })
            },
            // 获取案例详情
            getDetail() {
                if (!this.$route.query.id) {
                    return
                }
                getCaseAnalyseDetail(this.$route.query.id).then(({ code, message, data }) => {
                    if(code !== 1){
                        this.$Message.warning(message)
                        return
                    }
                    this.caseDetail = data
                    this.addBreadItem({ name: this.caseDetail.name });
                    let list = data.relations || []
                    let toolList = [], documentList = [], videoList = []
                    list.forEach(item => {
                        if (item.type === 1) {
                            toolList.push(item)
                        } else if (item.type === 2) {
                            documentList.push(item)
                        } else {
                            videoList.push(item)
                        }
                    })
                    this.toolList = toolList
                    this.documentList = documentList
                    if (data.iconPath) {
                        this.imageList = [{
                            path: data.iconPath
                        }]
                    }
                    this.videoList = videoList
                    this.formValidate = Object.assign(JSON.parse(JSON.stringify(data)), {
                        fileListIDs: documentList.map(item => item.id).join()
                    })
                    this.getProjectDetail()
                }).catch(() => {
                    this.$Message.error('获取案例详情异常')
                })
            }
        },
        beforeDestroy() {
            clearTimeout(this.timeOut)
            clearTimeout(this.countdownTimer)
        }
    }
</script>
<style scoped>
    .demo-tabs-style1 > .ivu-tabs-card > .ivu-tabs-content {
        height: 120px;
        margin-top: -16px;
    }

    .demo-tabs-style1 > .ivu-tabs-card > .ivu-tabs-content > .ivu-tabs-tabpane {
        background: #fff;
        padding: 16px;
    }

    .demo-tabs-style1 > .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab {
        border-color: transparent;
    }

    .demo-tabs-style1 > .ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab-active {
        border-color: #fff;
    }

    .count-down {
        color: #ed4014;
    }

    .btn-group {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .page-wrap {
        height: 100%;
        min-height: 800px;
    }
    
    .page-content {
        background-color: #fff;
        border-radius: 10px;
        height: calc(100% - 24px);
    }
    
    .img-header {
        display: flex;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }
    
    .addressIcon {
        display: inline-block;
        height: 14px;
        width: 12px;
        background: url("../../assets/globalIcon/addressIcon.png") no-repeat center;
        background-size: 100% 100%;
        margin-bottom: -1px;
    }
    
    .content-wrap {
        overflow-x: hidden;
        overflow-y: auto;
        padding: 0 20px 20px 20px;
        height: calc(100% - 96px);
    }
    .left-hei {
        overflow-x: hidden;
        overflow-y: auto;
        /*padding-right: 8px;*/
        max-height: calc(100% - 66px);
        /*padding-top: 17px;*/
    }
    
    .title-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
    }
    
    .titleActive {
        border: 1px solid #1563C2 ;
    }
    
    .title-name {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    
    .page-wrap /deep/.editor .ql-container.ql-snow {
        overflow: hidden auto;
    }
    
    .page-wrap /deep/.editor .ql-editor {
        overflow: auto;
    }

    .mt20 {
        margin-top: 20px;
    }

    .mr6 {
        margin-right: 6px;
    }
</style>